package com.farm.shop.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.util.RandomUtil;
import com.farm.common.annotation.Log;
import com.farm.common.config.Config;
import com.farm.common.domain.FileDO;
import com.farm.common.service.FileService;
import com.farm.common.utils.*;
import com.farm.shop.constant.PageParam;
import com.farm.shop.dao.FarmShopDao;
import com.farm.shop.domain.FarmDishDO;
import com.farm.shop.domain.FarmRoomDO;
import com.farm.shop.domain.FarmShopDO;
import com.farm.shop.response.*;
import com.farm.shop.service.FarmDishService;
import com.farm.shop.service.FarmRoomService;
import com.farm.shop.service.FarmShopService;
import com.farm.system.dao.UserDao;
import com.farm.system.domain.UserDO;
import com.farm.system.service.UserService;
import com.farm.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 农家店铺表
 * 审核状态 1审核通过 2审核中
 *
 * @author chglee
 * @email 1992lcg@163.com
 * @date 2019-09-06 19:44:50
 */
@Slf4j
@Controller
@RequestMapping("/farm/farmShop")
public class FarmShopController {

    @Autowired
    private FarmShopService farmShopService;

    @Autowired
    UserDao userMapper;

    @Autowired
    FarmShopDao farmShopDao;

    @Autowired
    private UserService userService;

    @Autowired
    private FarmRoomService farmRoomService;

    @Autowired
    private FarmDishService farmDishService;

    @Autowired
    private FileService sysFileService;

    @Autowired
    private Config config;

    /**
     *  根据手机号查询店铺审核状态
     *
     * @param params  参数 手机号
     * @return         Result
     */
    @Log(value = " A根据手机号查询店铺审核状态")
    @ResponseBody
    @GetMapping(value = "/app/getStatusByMobile")
    public Result getStatusByPhone( @RequestParam Map<String, Object> params) {
        String mobile = (String) params.get("mobile");
        Map<String, Object> shopMap = new HashMap<>(2);
        shopMap.put("phone", mobile);
        List<FarmShopDO> shopStatus = farmShopDao.list(shopMap);

        if (shopStatus.size() == 0) {
            return Result.success(mobile + "不存在,请求失败");
        }

        Integer status = shopStatus.get(0).getStatus();

        log.info("status:" + status);

        if (status == 1) {
            // 审核成功
            StatusByPhone response = new StatusByPhone();

            Map<String, Object> userParams = new HashMap<>(2);
            userParams.put("mobile", mobile.trim());
            List<UserDO> users = userMapper.list(userParams);
            if (users.size() > 0) {
                log.info("该手机号已经审核成功,phone:{}", params.get("phone"));
                response.setStatus(1);
                response.setUserName(users.get(0).getUsername());
                response.setPassword(users.get(0).getPassword());
                return Result.success("您已经审核成功", response);
            }

        } else if (status == 2) {
            // 审核中  未审核
            StatusByPhone response = new StatusByPhone();
            response.setStatus(2);
            return Result.success("审核中", response);
        } else {
            StatusByPhone response = new StatusByPhone();
            response.setStatus(3);
            return Result.success("审核失败", response);
        }
        return null;
    }


    @ResponseBody
    @PostMapping(value = "/app/upload" )
    public Result upload(@RequestParam("file") MultipartFile file) {
        String fileName = file.getOriginalFilename();
        fileName = FileUtil.renameToUUID(fileName);

//       windows 测试环境
/*     FileDO sysFile = new FileDO(FileType.fileType(fileName), "http:/" + NetUtil.getLocalhost() + "/files/" + fileName, new Date());*/

//        Linux 环境
     FileDO sysFile = new FileDO(FileType.fileType(fileName),
                "http://106.54.101.235:80/files/" + fileName, new Date());
        try {
            String uploadPath = config.getUploadPath();
            FileUtil.uploadFile(file.getBytes(), uploadPath, fileName);
         log.info("服务器图片上传成功:{}" ,"http://106.54.101.235:80/files/" + fileName);

    /*     log.info("图片上传成功:{}" ,"http://localhost:80/files/" + fileName);*/

            File maxFile = cn.hutool.core.io.FileUtil.file(uploadPath + fileName);

            String minFileName = fileName.replace(".", "_min.");

            File minFile = cn.hutool.core.io.FileUtil.file(uploadPath + minFileName);

            // 等比例缩小
            ImgUtil.scale(maxFile , minFile ,0.5f);

        } catch (Exception e) {
            return Result.fail("上传失败");
        }

        if (sysFileService.save(sysFile) > 0) {
            return Result.success(sysFile.getUrl());
        }
        return Result.fail("上传失败");
    }

    /**
     * app 商家入驻
     *
     * @param params Result
     * @return Result
     */
    @Log(value = " A商家入驻")
    @ResponseBody
    @PostMapping(value = "/app/shopenter")
    public Result saveShopEnter(@RequestBody Map<String, Object> params) {

        FarmShopDO shopDO = new FarmShopDO();
        shopDO.setName(Convert.toStr(params.get("name")));
        shopDO.setPhone(Convert.toStr(params.get("phone")));
        shopDO.setTitle(Convert.toStr(params.get("title")));
        shopDO.setStorePhotos(Convert.toStr(params.get("storePhotos")));
        shopDO.setConsumption(Convert.toStr(params.get("consumption")));
        shopDO.setAccommodation(Convert.toInt(params.get("accommodation")));
        shopDO.setDiningRoom(Convert.toInt(params.get("diningRoom")));
        shopDO.setFarmName(Convert.toStr(params.get("farmName")));
        shopDO.setBusinessLicens(Convert.toStr(params.get("businessLicens")));
        shopDO.setAddress(Convert.toStr(params.get("address")));

        log.info("农家入驻请求数据:{}" , shopDO.toString());
        int result = farmShopService.save(shopDO);

        return Result.success(result > 0);
    }


    /**
     * 全局搜索
     *
     * @param params 参数
     * @return Result
     */
    @Log(value = " A全局搜索")
    @ResponseBody
    @GetMapping("/app/search")
    public Result getAppSearch(@RequestParam Map<String, Object> params) {
        String keyword = (String) params.get("keyword");

        List<FarmShopDO> shopSearch = farmShopService.search(keyword);
        List<FarmRoomDO> roomSearch = farmRoomService.search(keyword);
        List<FarmDishDO> dishSearch = farmDishService.search(keyword);

        PlumpSearch result = new PlumpSearch();
        result.setFarmShops(shopSearch);
        result.setFarmRooms(roomSearch);
        result.setFarmDishs(dishSearch);

        if (CollUtil.isEmpty(result.getFarmShops())
                && CollUtil.isEmpty(result.getFarmRooms())
                && CollUtil.isEmpty(result.getFarmDishs())) {
            Map<String, Object> hotParams = new HashMap<>();
            hotParams.put("status", 1);
            // 是否推荐   1推荐  2不推荐
            hotParams.put("recommend", 1);
            hotParams.put("updownStatus", 1);

            //查询列表数据
            Query query = new Query(hotParams);

            List<FarmShopDO> appHotFarms = farmShopService.list(query);
            return Result.success("抱歉，没有符合条件的商家和商品", appHotFarms);
        }
        return Result.success(result);
    }

    /**
     * App 获取美食农家列表
     * 1有 2没有
     */
    @Log(value = " A获取美食农家列表")
    @ResponseBody
    @GetMapping("/app/diningRoomFarms")
    public Result getAppDiningRoomFarms(@RequestParam Map<String, Object> params) {

        params.put("status", 1);
        //是否包含美食 1有 2没有
        params.put("diningRoom", 1);
        params.put("updownStatus", 1);
        int currPage = Integer.parseInt((String) params.get("page"));
        params.put("offset", (currPage - 1) * PageParam.LIMIT);
        params.put("limit", PageParam.LIMIT);

        //查询列表数据
        Query query = new Query(params);

        List<FarmShopDO> appAccommodationFarms = farmShopService.list(query);
        int total = farmShopService.count(query);
        PageUtils pageUtils = new PageUtils(total, currPage, appAccommodationFarms);
        return Result.success(pageUtils);
    }

    /**
     * App 获取住宿农家列表
     * 是否住宿   1有   2没有
     */
    @Log(value = " A获取住宿农家列表")
    @ResponseBody
    @GetMapping("/app/accommodationFarms")
    public Result getAppAccommodationFarms(@RequestParam Map<String, Object> params) {

        params.put("status", 1);
        //是否住宿   1有   2没有
        params.put("accommodation", 1);
        params.put("updownStatus", 1);
        int currPage = Integer.parseInt((String) params.get("page"));
        params.put("offset", (currPage - 1) * PageParam.LIMIT);
        params.put("limit", PageParam.LIMIT);

        //查询列表数据
        Query query = new Query(params);

        List<FarmShopDO> appAccommodationFarms = farmShopService.list(query);
        int total = farmShopService.count(query);
        PageUtils pageUtils = new PageUtils(total, currPage, appAccommodationFarms);
        return Result.success(pageUtils);
    }


    /**
     * App 查询 热门 农家列表
     *
     * @param params
     * @return Result
     */
    @Log(value = "A查询热门农家列表")
    @ResponseBody
    @GetMapping("/app/hotfarms")
    public Result getAppShopHot(@RequestParam Map<String, Object> params) {

        params.put("status", 1);
        // 是否推荐   1推荐  2不推荐
        params.put("recommend", 1);
        params.put("updownStatus", 1);
        int currPage = Integer.parseInt((String) params.get("page"));
        params.put("offset", (currPage - 1) * PageParam.LIMIT);
        params.put("limit", PageParam.LIMIT);

        //查询列表数据
        Query query = new Query(params);

        List<FarmShopDO> appHotFarms = farmShopService.list(query);
        int total = farmShopService.count(query);
        PageUtils pageUtils = new PageUtils(total, currPage, appHotFarms);
        return Result.success(pageUtils);
    }

    /**
     * App 获取农家详情
     * 1有 2没有
     */
    @Log(value = "A获取农家详情")
    @ResponseBody
    @GetMapping("/app/farmdetail/{farmId:\\d+}")
    public Result getAppFarmdetail(@PathVariable(value = "farmId") Long id) {

        FarmShopDO farmShopDO = farmShopService.get(id);
        FarmShop farmShop = FarmShopBeanMapper.mapNew(farmShopDO);
        if (farmShop == null) {
            return Result.ok();
        }

        return assemble(farmShop);

    }

    @GetMapping("/shopCount")
    @RequiresPermissions("farm:farmShop:shopCount")
    String FarmShopCount( Model model) {
        // 查询审核通过住宿农家 count
        Map<String,Object> params = new HashMap<>(6);
        params.put("accommodation", 1);
        params.put("status", 1);
        int accommodationCount = farmShopService.count(params);

        // 查询审核通过美食农家 count
        params.clear();
        params.put("diningRoom", 1);
        params.put("status", 1);
        int diningRoomCount = farmShopService.count(params);

        // 查询同时包括住宿 和 美食
        params.clear();
        params.put("accommodation", 1);
        params.put("diningRoom", 1);
        params.put("status", 1);
        int accommodationFood = farmShopService.count(params);

        model.addAttribute("accommodationCount", accommodationCount);
        model.addAttribute("diningRoomCount", diningRoomCount);
        model.addAttribute("accommodationFood", accommodationFood);

        return "farm/farmShop/farmShopCount";
    }

    /**
     * 农家统计
     *
     * @param params 查询参数
     * @return PageUtils
     */
    @ResponseBody
    @GetMapping("/getShopCount")
    @RequiresPermissions("farm:farmShop:shopCount")
    public PageUtils getShopCount(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);

        List<FarmShopDO> farmShopList = farmShopService.list(query);
        int total = farmShopService.count(query);
        PageUtils pageUtils = new PageUtils(farmShopList, total);
        return pageUtils;
    }

    @GetMapping("/shopHot")
    @RequiresPermissions("farm:farmShop:shopHot")
    String FarmShopHot() {
        return "farm/farmShop/farmShopHot";
    }

    /**
     * 查询 热门 农家列表
     * 1推荐  2不推荐
     *
     * @param params 查询参数
     * @return PageUtils
     */
    @Log(value = "B查询热门农家列表")
    @ResponseBody
    @GetMapping("/getShopHot")
    @RequiresPermissions("farm:farmShop:shopHot")
    public PageUtils getShopHot(@RequestParam Map<String, Object> params) {
        params.put("status", 1);
        params.put("recommend", 1);
        params.put("updownStatus", 1);
        //查询列表数据
        Query query = new Query(params);

        List<FarmShopDO> farmShopList = farmShopService.list(query);
        int total = farmShopService.count(query);
        PageUtils pageUtils = new PageUtils(farmShopList, total);
        return pageUtils;
    }

    @GetMapping("/shopStatus")
    @RequiresPermissions("farm:farmShop:shopStatus")
    String FarmShopStatus() {
        return "farm/farmShop/farmShopStatus";
    }

    /**
     * 获取正在审核的农家
     *
     * @param params 查询参数
     * @return PageUtils
     */
    @Log(value = "B获取正在审核的农家列表")
    @ResponseBody
    @GetMapping("/getShopReview")
    @RequiresPermissions("farm:farmShop:shopStatus")
    public PageUtils getShopReview(@RequestParam Map<String, Object> params) {
        params.put("status", 2);
        //查询列表数据
        Query query = new Query(params);

        List<FarmShopDO> farmShopList = farmShopService.listShopReview(query);
        int total = farmShopService.count(query);
        PageUtils pageUtils = new PageUtils(farmShopList, total);
        return pageUtils;
    }

    @GetMapping()
    @RequiresPermissions("farm:farmShop:farmShop")
    String FarmShop() {
        UserDO user = ShiroUtils.getUser();
        return  user.getDeptId() == 16 ? "farm/farmShop/farmShop"
                : "farm/farmShop/shop";

    }

    /**
     * 审核成功的农家列表
     *
     *  按照入驻时间倒叙  上下架状态升序  下架后的店铺排在最后面 查询
     *
     * @param params 查询参数
     * @return PageUtils
     */
    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("farm:farmShop:farmShop")
    public PageUtils list(@RequestParam Map<String, Object> params) {

        boolean flagShopType = params.containsKey("shopType");
        if (flagShopType) {
            // 查询审核成功的农家 并且为上架shopType
            if (params.get("shopType").equals("正常")) {
                params.put("status", 1);
            } else if (params.get("shopType").equals("下架")) {
                params.put("updownStatus", 2);
            }
        }

       // params.put("updownStatus", 1);


        //查询列表数据
        Long userId = ShiroUtils.getUserId();

        // 类型查询 暂时借用 address 字段接收参数
        boolean flagAddress = params.containsKey("address");
        if (flagAddress){
            if(params.get("address") == ""){
                params.remove("address");
            } else {
                if (params.get("address").equals("住宿")){
                    params.remove("address");
                    params.put("accommodation" ,1);
                    params.put("diningRoom" ,2);
                } else if (params.get("address").equals("住宿美食")){
                    params.remove("address");
                    params.put("accommodation" ,1);
                    params.put("diningRoom" ,1);
                } else{
                    params.remove("address");
                    params.put("diningRoom", 1);
                    params.put("accommodation", 2);
                }
            }
        }

        if (userId != 1){
            params.remove("status");
            params.put("userId", userId);
            Query query = new Query(params);
            List<FarmShopDO> farmShopByUserId = farmShopService.getFarmShopByUserId(userId);
            PageUtils pageUtils = new PageUtils(farmShopByUserId, farmShopByUserId.size());
            return pageUtils;

        }
        Query query = new Query(params);
        List<FarmShopDO> farmShopList = farmShopService.list(query);
        int total = farmShopService.count(query);
        PageUtils pageUtils = new PageUtils(farmShopList, total);
        return pageUtils;
    }

    @GetMapping("/add")
    @RequiresPermissions("farm:farmShop:add")
    String add() {
        return "farm/farmShop/add";
    }

    @Log(value = "B查看店铺地址")
    @GetMapping("/getLocation/{id}")
    String getLocation(@PathVariable("id") Long id, Model model) {
        FarmShopDO farmShop = farmShopService.get(id);
        log.info(farmShop.toString());
        model.addAttribute("address", farmShop.getAddress());
        model.addAttribute("lng", farmShop.getLng());
        model.addAttribute("lat", farmShop.getLat());
        return "farm/farmShop/shopAddress";
    }

    @GetMapping("/edit/{id}")
    @RequiresPermissions("farm:farmShop:edit")
    String edit(@PathVariable("id") Long id, Model model) {
        FarmShopDO farmShop = farmShopService.get(id);
        String[] scenicpictureArr = farmShop.getStorePhotos().split(",");
        if (scenicpictureArr.length==1&&"".equals(scenicpictureArr[0])){
            scenicpictureArr = null;
        }
        model.addAttribute("farmShop", farmShop);
        model.addAttribute("scenicpictureArr", scenicpictureArr);

        UserDO user = ShiroUtils.getUser();
        return  user.getDeptId() == 16 ? "farm/farmShop/edit"
                : "farm/farmShop/farmEdit";
    }

    @GetMapping("/preview/{id}")
    @RequiresPermissions("farm:farmShop:edit")
    String preview(@PathVariable("id") Long id, Model model) {
        Map<String, Object> params = new HashMap<>();
        params.put("shopId",id);
        Query query = new Query(params);
        FarmShopDO farmShop = farmShopService.get(id);
        List<FarmRoomDO> farmRoomDOList = farmRoomService.list(query);
        for (FarmRoomDO farmRoomDO : farmRoomDOList) {
            farmRoomDO.setRoomPhotos(farmRoomDO.getRoomPhotos().split(",")[0]);
        }
        List<FarmDishDO> farmDishDOList = farmDishService.list(query);
        for (FarmDishDO farmDish : farmDishDOList) {
            farmDish.setDishPhotos(farmDish.getDishPhotos().split(",")[0]);
            farmDish.setDishDescribe(farmDish.getDishDescribe() + " " + farmDish.getType());
        }
        String[] scenicpictureArr = farmShop.getStorePhotos().split(",");
        int length = farmShop.getTitle().length();
        farmShop.setBusinessLicens(farmShop.getTitle().substring(0, 28));
        farmShop.setConsumption(farmShop.getTitle().substring(28, length));
        model.addAttribute("farmShop", farmShop);
        model.addAttribute("scenicpictureArr", scenicpictureArr);
        model.addAttribute("farmRoomDOList", farmRoomDOList);
        model.addAttribute("farmDishDOList", farmDishDOList);
        model.addAttribute("farmId", id);
        return "farm/farmShop/previewShop";
    }


    @GetMapping("/room/{id}")
    @RequiresPermissions("farm:farmShop:edit")
    String room(@PathVariable("id") Long id, Model model) {
        model.addAttribute("farmId", id);
        return "farm/farmShop/room";
    }

    @GetMapping("/dish/{id}")
    @RequiresPermissions("farm:farmShop:edit")
    String dish(@PathVariable("id") Long id, Model model) {
        model.addAttribute("farmId", id);
        return "farm/farmShop/dish";
    }

    /**
     * 保存
     */
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("farm:farmShop:add")
    public R save(FarmShopDO farmShop) {
//        人均消费
        farmShop.setConsumption(farmShop.getConsumption() );
        if (farmShopService.save(farmShop) > 0) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 修改
     */
    @Log(value = "B修改农家信息")
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("farm:farmShop:edit")
    public R update(FarmShopDO farmShop) {
        farmShopService.update(farmShop);
        return R.ok();
    }

    /**
     * 审核通过按钮
     */
    @ResponseBody
    @RequestMapping("/pass")
    @RequiresPermissions("farm:farmShop:edit")
    public R pass(@RequestParam("ids[]") Long id) {
        boolean result = farmShopService.updateStatusById(id);

        // 保存用户到数据库
        UserDO user = new UserDO();
        user.setDeptId(52L);
        user.setName("农家管理员");
        String phone = farmShopService.get(id).getPhone().trim();
        user.setUsername(phone);
        user.setStatus(1);
        String password = RandomUtil.randomString(6);
        user.setPassword(password);
        user.setMobile(phone);
        user.setRoleIds(CollUtil.newArrayList(3L));
        userService.save(user);

        // 店铺和用户管理
        Long userId = user.getUserId();
        return  farmShopDao.passStatusAndUserId(userId,id) > 0
                    ? R.ok() : R.error();
    }

    /**
     * 审核通过按钮
     */
    @ResponseBody
    @RequestMapping("/nopass")
    @RequiresPermissions("farm:farmShop:edit")
    public R nopass(@RequestParam("ids[]") Long id) {
        boolean result = farmShopService.nopassStatusById(id);

        return result ? R.ok() : R.error();
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("farm:farmShop:remove")
    public R remove(Long id) {
        if (farmShopService.remove(id) > 0) {
            return R.ok();
        }
        return R.error();
    }

    /**
     * 删除
     */
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("farm:farmShop:batchRemove")
    public R remove(@RequestParam("ids[]") Long[] ids) {
        farmShopService.batchRemove(ids);
        return R.ok();
    }

    /**
     * 组装查询结果
     *
     * @param farmShop 农家详情
     * @return 农家详情
     */
    private Result<PlumpFarm> assemble(FarmShop farmShop) {

        // 获取房间信息
        Map<String, Object> roomParms = new HashMap<>(16);
        roomParms.put("shopId", farmShop.getId());
        List<FarmRoomDO> farmRooms = farmRoomService.list(roomParms);


        List<FarmRoom> mapNewfarmRooms = farmRooms.stream().map(FarmRoomBeanMapper::mapNew).collect(Collectors.toList());
        farmShop.setFarmRooms(mapNewfarmRooms);

        // 获取菜品信息
        Map<String, Object> dishParms = new HashMap<>(16);

        dishParms.put("shopId", farmShop.getId());
        List<FarmDishDO> farmDishs = farmDishService.list(dishParms);
        List<Dish> mapNewfarmDishs = farmDishs.stream().map(FarmDishBeanMapper::mapNew).collect(Collectors.toList());
        farmShop.setDishs(mapNewfarmDishs);


        PlumpFarm data = new PlumpFarm();
        data.setWrapper(farmShop);

        return Result.success(data);
    }

}
